<template>
  <el-row>
    <el-col :span="10"><div class="fix">
      <el-card class="fix-card">
        <div class="content_top">
          <div class="device_check">
            <p class="dev_code">设备唯一码</p>
            <el-input
                class="dev_input"
                placeholder="请输入或扫码"
                suffix-icon="el-icon-saoma"
                v-model="device_input"
                clearable>
            </el-input>
            <el-button type="primary" class="dev_button" @click="show_salesreturn">确定</el-button>
          </div>
          <div class="model_code">
            <p class="model_head">关联机型代码</p>
            <el-select v-model="value" filterable allow-create clearable placeholder="请选择" class="model_select">
              <el-option
                  v-for="item in options"
                  :key="item.index"
                  :label="item.label"
                  :value="item.index">
              </el-option>
            </el-select>
            <p class="net_code">已关联{{GLnum}}个机型代码</p>
          </div>
        </div>
        <div class="content_bottom">
          <div class="head">
            <h3 class="fix_title"></h3>
          </div>
          <el-table
              :data="salesreturn_list"
              style="width: 100%"
              height="400px" highlight-current-row @current-change="handleCurrentChange" @selection-change="handleSelectionChange" v-loading="loading1">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column v-for="(val, key) in salesreturn_label" :prop="key" :label="val" :key="key" :width="getColumnWidth(key)" :show-overflow-tooltip="true"/>
          </el-table>
          <div class="button-container">
            <el-button type="primary" class="dev_button" @click="openDialog">维修</el-button>
            <el-button class="dev_button cancel">取消</el-button>
          </div>
          <el-dialog
              :title="'确认对设备[唯一码:'+submitDevGuid+']进行维修'"
              class="dialog1"
              :visible.sync="dialogVisible1"
              width="50%" center>
            <div class="input-container1">
              <div class="group1">
                <p>更换设备唯一码</p>
                <el-input
                    class="repairGuid"
                    placeholder="请输入或扫码"
                    suffix-icon="el-icon-saoma"
                    v-model="repairDevGuid"
                    clearable>
                </el-input>
              </div>
              <div class="group2">
                <p>修改硬件信息</p>
                <el-input
                    class="repairDh"
                    placeholder="请输入硬件信息"
                    v-model="repairDevHardware"
                    clearable>
                </el-input>
              </div>
            </div>
            <div class="input-container2">
              <div class="group1">
                <p>变更核心模块版本</p>
                <el-input
                    class="repairSw1"
                    placeholder="请输入核心模块版本"
                    v-model="repairDevSoftware1"
                    clearable>
                </el-input>
              </div>
              <div class="group2">
                <p>变更报警模块版本</p>
                <el-input
                    class="repairSw2"
                    placeholder="请输入报警模块版本"
                    v-model="repairDevSoftware2"
                    clearable>
                </el-input>
              </div>
            </div>
            <div class="input-container3">
              <p>故障描述</p>
              <el-input
                  class="repairFd"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入故障描述"
                  v-model="devFailureDesc"
                  clearable>
              </el-input>
            </div>
            <div class="input-container4">
              <p>维修描述</p>
              <el-input
                  class="repairDs"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入维修描述"
                  v-model="repairDesc"
                  clearable>
              </el-input>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog1">取消</el-button>
              <el-button type="primary" @click="handleConfirm1">确定</el-button>
            </span>
          </el-dialog>
          <el-dialog
              :title="'确认对'+selectedNum+'台设备进行维修'"
              class="dialog1"
              :visible.sync="dialogVisible2"
              width="50%" center>
            <div class="input-container1">
              <div class="group1">
                <p>更换设备唯一码</p>
                <el-input
                    class="repairGuid"
                    placeholder="仅支持单台操作"
                    suffix-icon="el-icon-saoma"
                    :disabled="true"
                    readonly>
                </el-input>
              </div>
              <div class="group2">
                <p>修改硬件信息</p>
                <el-input
                    class="repairDh"
                    placeholder="请输入硬件信息"
                    v-model="repairDevHardware"
                    clearable>
                </el-input>
              </div>
            </div>
            <div class="input-container2">
              <div class="group1">
                <p>变更核心模块版本</p>
                <el-input
                    class="repairSw1"
                    placeholder="请输入核心模块版本"
                    v-model="repairDevSoftware1"
                    clearable>
                </el-input>
              </div>
              <div class="group2">
                <p>变更报警模块版本</p>
                <el-input
                    class="repairSw2"
                    placeholder="请输入报警模块版本"
                    v-model="repairDevSoftware2"
                    clearable>
                </el-input>
              </div>
            </div>
            <div class="input-container3">
              <p>故障描述</p>
              <el-input
                  class="repairFd"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入故障描述"
                  v-model="devFailureDesc"
                  clearable>
              </el-input>
            </div>
            <div class="input-container4">
              <p>维修描述</p>
              <el-input
                  class="repairDs"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入维修描述"
                  v-model="repairDesc"
                  clearable>
              </el-input>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="closeDialog2">取消</el-button>
              <el-button type="primary" @click="handleConfirm2">确定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-card>
    </div></el-col>
    <el-col :span="14"><div class="detail">
      <el-card class="detail-card">
        <el-empty v-if="!selectedDevice" description="暂无设备信息" style="height: 800px">
          <template #image>
            <div class="custom-empty-content">
              <img src="https://img2.imgtp.com/2024/04/03/fhG64MFW.png" class="custom-image">
            </div>
          </template>
        </el-empty>
        <div v-else>
          <div class="head">
            <h3 class="detail_title"></h3>
          </div>
          <div class="detail">
            <el-descriptions class="dt" :columns="2" size="mini" v-loading="loading2">
              <el-descriptions-item label="设备名称" span="2">
                {{ device_detail.devType }}
                <el-tag
                    size="small"
                    :type="getTagType(parseInt(device_detail.devState))"
                    class="dt_tag">
                  {{ getTagLabel(parseInt(device_detail.devState)) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="设备唯一码" span="2">{{ device_detail.devGuid }}</el-descriptions-item>
              <el-descriptions-item label="工单号" span="2">
                {{ device_detail.workOrderCode }}
                <i class="el-icon-list" @click="openMessageBox" style="color:#165DFF "></i>
              </el-descriptions-item>
              <el-descriptions-item label="箱子编号" span="2">
                {{ device_detail.boxCode }}
                <i class="el-icon-list"></i>
              </el-descriptions-item>
              <el-descriptions-item label="销售单号" span="2">
                {{ device_detail.saleCode }}
                <i class="el-icon-list"></i>
              </el-descriptions-item>
              <el-descriptions-item label="产品序列号" span="2">{{ device_detail.devSerialNumber }}</el-descriptions-item>
              <el-descriptions-item label="机型代码" span="2">{{ device_detail.devCode }}</el-descriptions-item>
              <el-descriptions-item label="硬件信息" span="2">{{ device_detail.devHardware }}</el-descriptions-item>
              <el-descriptions-item label="生产时间" span="2">{{ device_detail.mfgTime }}</el-descriptions-item>
              <el-descriptions-item label="核心模块版本" span="2">{{ device_detail.devSoftware1 }}</el-descriptions-item>
              <el-descriptions-item label="客户名称" span="2">{{ device_detail.client }}</el-descriptions-item>
              <el-descriptions-item label="报警模块版本" span="2">{{ device_detail.devSoftware2 }}</el-descriptions-item>
              <el-descriptions-item label="操作员" span="2">{{ device_detail.user }}</el-descriptions-item>
            </el-descriptions>

          </div>
          <div class="tabs">
            <el-tabs v-model="activeName">
              <el-tab-pane name="first" label="入库记录">
                <el-table :data="instock_list" style="width: 100%" max-height="500px">
                  <el-table-column v-for="(val, key) in instock_label" :prop="key" :label="val" :key="key" :width="getColumnWidth(key)"/>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="出库记录" name="second">
                <el-table :data="outstock_list" style="width: 100%" max-height="500px" >
                  <el-table-column v-for="(val, key) in outstock_label" :prop="key" :label="val" :key="key" :width="getColumnWidth(key)"/>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="退货记录" name="third">
                <el-table :data="retstock_list" style="width: 100%" max-height="500px">
                  <el-table-column v-for="(val, key) in retstock_label" :prop="key" :label="val" :key="key" :width="getColumnWidth(key)"/>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="维修记录" name="fourth">
                <el-table :data="repair_list" style="width: 100%" max-height="500px">
                  <el-table-column v-for="(val, key) in repair_label" :prop="key" :label="val" :key="key" />
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="返工记录" name="fifth">
                <el-table :data="rework_list" style="width: 100%" max-height="500px">
                  <el-table-column v-for="(val, key) in rework_label" :prop="key" :label="val" :key="key" />
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-card>
    </div></el-col>
  </el-row>
</template>
<script>
export default {
  data() {
    return {
      selectedNum:0,
      submitDevice:0,
      submitList:[],
      selected_devId:0,
      submitDevGuid:'',
      salesindex:1,
      activeName:'first',
      loading1:false,
      loading2:false,
      GLnum:0,
      devFailureDesc:'',
      repairDesc:'',
      repairDevSoftware1:'',
      repairDevSoftware2:'',
      repairDevGuid:'',
      repairDevHardware:'',
      device_input: "",
      value:"",
      selectedDevice:false,
      dialogVisible1:false,
      dialogVisible2:false,
      options:[
        {index:1,label:'B150'},
        {index:2,label:'B151'},
        {index:3,label:'B152'}
      ],
      salesreturn_list:[],
      salesreturn_label:{
        index: "序号",
        devCode: "机型代码",
        devGuid: "设备唯一码",
        client: "客户名称",
        devTypename: "维修设备"
      },
      instock_list: [], // 入库列表数据
      instock_label: {
        index: "序号",
        devCode: "机型代码",
        boxCode: "箱子编号",
        time: "入库时间",
        worker: "操作员"
      },
      outstock_list:[],
      outstock_label: {
        index: "序号",
        client: "客户名称",
        outstockTime: "出库时间",
        worker: "操作员"
      },
      retstock_list:[],
      retstock_label:{
        index: "序号",
        reason: "退货原因",
        time: "退货时间",
        worker: "操作员",
        description: "备注"
      },
      repair_list:[],
      repair_label:{
        index: "序号",
        c_device: "更换设备唯一码",
        c_message: "修改硬件信息",
        c_h_version: "变更核心模块版本",
        c_b_version: "变更报警模块版本",
        content: "故障内容",
        solution: "解决方案",
        time: "维修时间"
      },
      rework_list:[],
      rework_label:{
        index: "序号",
        c_device: "更换设备唯一码",
        c_message: "修改硬件信息",
        c_h_version: "变更核心模块版本",
        c_b_version:"变更报警模块版本",
        content: "返工内容",
        time: "返工时间",
        worker: "操作员",
        description: "备注"
      },
      device_detail:{
        devType:'',
        devGuid:'',
        workOrderCode:'',
        boxCode:'',
        devSerialNumber:'',
        devCode:'',
        devHardware:'',
        mfgTime:'',
        devSoftware1:'',
        devSoftware2:'',
        client:'',
        user:'',
        devState:'',
        saleCode:''
      },
    };
  },
  methods: {
    handleCurrentChange(val) {
      this.selectedDevice = true;
      this.fetchDetailInfo(val.devId);
    },
    openMessageBox() {
      this.dialogVisible = true;
    },
    getColumnWidth(key) {
      // 返回不同列的宽度
      if (key === 'index') {
        return '50px'; // 设置boxCode列的宽度为150px
      }
    },
    openDialog() {
      console.log(this.selectedNum);
      console.log('id'+ this.submitDevice);
      console.log('list'+ this.submitList);
      if(this.selectedNum === 0)
      {
        this.$message({
          message: '请选择设备!',
          type: 'error'
        });
      }
      else if(this.selectedNum === 1)
      {
        this.dialogVisible1 = true;
      }
      else {
        this.dialogVisible2 = true;
      }
    },
    closeDialog1() {
      this.dialogVisible1 = false;
    },
    handleConfirm1() {
      this.dialogVisible1 = false;
    },
    closeDialog2() {
      this.dialogVisible2 = false;
    },
    handleConfirm2() {
      this.dialogVisible2 = false;
    },
    handleSelectionChange(val) {
      console.log(val);
      this.salesreturn_list.forEach(item => {
        item.selected = false;
      });
      val.forEach(item => {
        item.selected = true;
      });
      this.$nextTick(() => {
        this.getSelectedNum();
      });
    },
    getSelectedNum(){
      this.submitDevice = null;
      this.submitList = [];
      let selectedItems = this.salesreturn_list.filter(item => item.selected);
      if (selectedItems.length === 1) {
        // 如果只有一个被选择，记录它在 submitDevice 中。
        this.submitDevice = selectedItems[0].devId;
        this.submitDevGuid = selectedItems[0].devGuid;
      } else {
        // 如果没有被选中的项，或者选中的项多于一项，将所有选中的项的devId存入submitList中
        this.submitList = selectedItems.map(item => item.devId);
      }

      // 获取选中的个数
      this.selectedNum = selectedItems.length;
    },
    show_salesreturn() {
      if (!this.device_input) {
        this.$message({
          message: '输入框不能为空！',
          type: 'warning'
        });
        return; // 结束函数执行
      }
      this.loading1 = true;
      this.$axios.get('/api/Device/ListByGuid',{
        params:{
          devGuid:this.device_input
        },
        headers:{
          'Accept': 'application/json',
          'Content-Type': "application/json;charset=UTF-8",
          'token':this.token
        }
      }).then(res=>{
        console.log(res.data);
        // 遍历响应中的body数组
        if(res.data.code === -99)
        {
          this.$message({
            message: '登录已过期',
            type: 'error'
          });
          this.$router.push('/login');
        }
        else if(res.data.code === 0)
        {
          this.GLnum = 0;
          this.options=[];
          this.GLnum = res.data.body.data.length;
          if(this.GLnum > 1)
          {
            this.options = res.data.body.data.map(item => ({value: item.devCode, label: item.devCode}));
            this.$message({
              message: '该唯一码对应多个机型代码，请先筛选',
              type: 'warning'
            });
          }
          else{
            this.options = res.data.body.data.map(item => ({value: item.devCode, label: item.devCode}));
            Promise.all(res.data.body.data.map(item=>{
              if(item.devCode === this.value || this.value === '')
              {
                let newdata={
                  index:this.salesindex++,
                  devCode:item.devCode,
                  saleCode:item.saleCode,
                  client: item.client,
                  devTypename: item.box_Type.devTypeName,
                  devGuid: item.devGuid,
                  selected:false,
                  devId:0
                };
                return this.getDevId(newdata.devGuid)
                    .then(devId => {
                      newdata.devId = devId;
                      return newdata;
                    })
                    .catch(error => {
                      console.error("Error:", error);
                      return newdata;
                    });
              }
            })).then(dataWithIds => {
              this.salesreturn_list.push(...dataWithIds.filter(Boolean));
              this.loading1 = false;
            });
          }
        }
        else
        {
          this.$message({
            message: res.data.msg,
            type: 'error'
          });
        }
      }).catch(err=>{
        console.log(err);
        this.$message({
          message: err,
          type: 'error'
        });
      })
    },
    getDevId(devGuid) {
      return new Promise((resolve, reject) => {
        this.$axios.get('/api/Device/InfoByGuid', {
          params: {
            devGuid: devGuid
          },
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
            'token': this.token
          }
        }).then(res => {
          console.log(res.data);
          if (res.data.code === 0) {
            this.selected_devId = res.data.body.devId;
            resolve(this.selected_devId); // 将this.selected_devId作为参数传递给resolve
          }
          else if(res.data.code === -99)
          {
            this.$message({
              message: '登录已过期',
              type: 'error'
            });
            this.$router.push('/login');
          }
          else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
            reject(res.data.msg); // 异步操作失败，使用 reject 返回错误信息
          }
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          });
          reject(err); // 捕获到错误，使用 reject 返回错误信息
        });
      });
    },
    fetchDetailInfo(devId) {
      this.loading2 = true;
      // 发送 GET 请求，获取详细信息
      this.$axios.get('/api/Device/InfoById', {
        params: {
          devId: devId
        },
        headers:{
          'Accept': 'application/json',
          'Content-Type': "application/json;charset=UTF-8",
          'token':this.token
        }
      })
          .then(res => {
            // 处理响应数据
            console.log(res.data);
            this.device_detail.boxCode = this.ifboxCodeNull(res.data.body.box_Record);
            this.device_detail.user = res.data.body.user.userName;
            this.device_detail.devCode = res.data.body.devCode;
            this.device_detail.devGuid = res.data.body.devGuid;
            this.device_detail.devHardware = res.data.body.devHardware;
            this.device_detail.devSerialNumber = res.data.body.devSerialNumber;
            this.device_detail.devSoftware1 = res.data.body.devSoftware1;
            this.device_detail.devSoftware2 = res.data.body.devSoftware2;
            this.device_detail.mfgTime = res.data.body.mfgTime;
            this.device_detail.client = res.data.body.client;
            this.device_detail.workOrderCode = res.data.body.workOrderCode;
            this.device_detail.devState = res.data.body.devState;
            this.device_detail.saleCode = res.data.body.saleCode;
            this.device_detail.devType = res.data.body.devType.devTypeName;

            this.instock_list = [];
            res.data.body.instock.forEach(item => {
              let newData = {
                index: item.instockId,
                devCode: item.device.devCode,
                boxCode: item.box.boxCode,
                time: item.instockTime,
                worker: item.user.userName,
              };
              this.instock_list.push(newData);
            });
            this.outstock_list = [];
            res.data.body.outstock.forEach(item => {
              let newData = {
                index: item.outstockId,
                client: item.device.client,
                outstockTime: item.outstockTime,
                worker: item.user.userName,
              };
              this.outstock_list.push(newData);
            });
            this.retstock_list=[];
            res.data.body.retstock.forEach(item => {
              let newData = {
                index: item.retstockId,
                reason: item.retstockReason,
                time: item.retstockTime,
                worker: item.user.userName,
              };
              this.retstock_list.push(newData);
            });
            this.loading2 = false;
          })
          .catch(error => {
            console.error('获取详细信息失败:', error);
          });
    },
    getTagType(devState) {
      if (devState === 1) {
        return 'success';
      } else if (devState === 2) {
        return '';
      } else if (devState === 3) {
        return 'warning';
      } else if (devState === 4) {
        return 'danger';
      } else {
        return "";
      }
    },
    getTagLabel(devState){
      if (devState === 1) {
        return "生产完成";
      } else if (devState === 2) {
        return "入库";
      } else if (devState === 3) {
        return "出库";
      } else if (devState === 4) {
        return "报废";
      } else {
        return "未知状态";
      }
    },
    ifboxCodeNull(item){
      if(item==null)
      {
        return '-';
      }
      else
      {
        return item.boxCode;
      }
    },
  },
  created() {
    this.token = localStorage.getItem('token')
  },
};
</script>
<style lang="less" scoped>
.fix {
  .fix-card {
    .content_top {
      margin-bottom: 80px;
      .device_check {
        margin-top: 20px; /* 向上移动内容*/
        margin-left: 20px;
        display: flex;
        align-items: center; /* 垂直居中 */
      }
      .model_code {
        margin-top: 40px;
        margin-left: 20px;
        display: flex;
        align-items: center; /* 垂直居中 */
        .model_head {
          font-size: 14px;
          color: #999999;
          width: 30%; /* 设置 p 元素的宽度比例 */
        }
        .net_code {
          font-size: 14px;
          color: #999999;
          margin-left: 10px;
        }
      }
    }
    .content_bottom {
      .button-container{
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
}
.dialog1 {
  display: flex;
  flex-direction: column;
  .input-container1 {
    display: flex;
    justify-content: space-between;
    padding: 5px;
    .group1 {
      display: flex;
      flex-direction: row; /*给组内的元素设置行式布局*/
      align-items: center; /*垂直对齐中心*/
      p{
        color: #D90505;
        white-space: nowrap;
        margin-right: 10px;
      }
    }
    .group2 {
      display: flex;
      flex-direction: row; /*给组内的元素设置行式布局*/
      align-items: center; /*垂直对齐中心*/
      p{
        white-space: nowrap;
        margin-right: 10px;
      }
    }
  }
  .input-container2 {
    display: flex;
    justify-content: space-between;
    padding: 5px;
    .group1 {
      display: flex;
      flex-direction: row;
      align-items: center;
      p{
        white-space: nowrap;
        margin-right: 10px;
      }
    }
    .group2 {
      display: flex;
      flex-direction: row;
      align-items: center;
      p{
        white-space: nowrap;
        margin-right: 10px;
      }
    }
  }
  .input-container3 {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 5px;
    p{
      white-space: nowrap;
      margin-right: 10px;
    }
  }
  .input-container4 {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 5px;
    p{
      white-space: nowrap;
      margin-right: 10px;
    }
  }
}
.detail {
  margin-left: 10px;
}
.fix_title::before {
  content: '待维修列表';
  display: inline; /* 将 display 属性设置为 inline */
  width: auto; /* 让宽度自适应文字长度 */
  padding-left: 10px; /* 可以调整文字与竖杠的间距 */
  border-left: 3px solid #409EFF; /* 使用边框来模拟竖杠 */
  //position: relative; /* 设置相对定位 */
  //top: 50px; /* 调整标题向上偏移的距离 */
}
.detail_title::before {
  content: '设备履历表';
  display: inline; /* 将 display 属性设置为 inline */
  width: auto; /* 让宽度自适应文字长度 */
  padding-left: 10px; /* 可以调整文字与竖杠的间距 */
  border-left: 3px solid #409EFF; /* 使用边框来模拟竖杠 */
  //position: relative; /* 设置相对定位 */
  //top: 50px; /* 调整标题向上偏移的距离 */
}
</style>